package com.hhf.feiojcodesandbox.service.impl.old;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.WordTree;
import com.hhf.feiojcodesandbox.model.ExecuteCodeRequest;
import com.hhf.feiojcodesandbox.model.ExecuteCodeResponse;
import com.hhf.feiojcodesandbox.model.ExecuteMessage;
import com.hhf.feiojcodesandbox.model.JudgeInfo;
import com.hhf.feiojcodesandbox.service.CodeSandbox;
import com.hhf.feiojcodesandbox.service.impl.JavaNativeCodeSandbox;
import com.hhf.feiojcodesandbox.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @Author hhf
 * @Date 2024/10/27
 * @Description Java原生代码沙箱
 */
@Slf4j
@Deprecated
public class JavaNativeCodeSandboxOld implements CodeSandbox {

    private static final String GLOBAL_CODE_DIR_NAME = "tempCode";

    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    private static final List<String> BLACKLIST = Arrays.asList("Files", "exec");

    private static final String SECURITY_MANAGER_PATH = "E:\\code\\project\\yupi\\OJ在线判题系统\\feioj-code-sandbox\\src\\main\\resources\\security";

    private static final String SECURITY_MANAGER_CLASS_NAME = "MySecurityManager";


    private static final WordTree WORD_TREE = new WordTree();

    static {
        //初始化字典树
        WORD_TREE.addWords(BLACKLIST);
    }


    public static void main(String[] args) {
        JavaNativeCodeSandbox javaNativeCodeSandbox = new JavaNativeCodeSandbox();

        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setInputList(Arrays.asList("1 2", "1 3"));
//        String code = ResourceUtil.readStr("testCode/simpleComputeArgs/Add.java", StandardCharsets.UTF_8);
//        String code = ResourceUtil.readStr("testCode/unSafe/TimeExceed.java", StandardCharsets.UTF_8);
//        String code = ResourceUtil.readStr("testCode/unSafe/MemoryExceed.java", StandardCharsets.UTF_8);
        String code = ResourceUtil.readStr("testCode/unSafe/ReadFile.java", StandardCharsets.UTF_8);
//        String code = ResourceUtil.readStr("testCode/unSafe/WriteFile.java", StandardCharsets.UTF_8);
//        String code = ResourceUtil.readStr("testCode/unSafe/Exec.java", StandardCharsets.UTF_8);
        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");


        ExecuteCodeResponse response = javaNativeCodeSandbox.executeCode(executeCodeRequest);
        if (response == null) {
            log.error("发生错误");
        } else {
            log.info(response.toString());
        }
    }

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {

        //开启 Security Manager,不推荐,会拦截项目的代码
//        System.setSecurityManager(new MySecurityManager.java());

        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();

        //校验用户的code是否包含敏感词汇
//        FoundWord foundWord = WORD_TREE.matchWord(code);
//        if (foundWord != null) {
//            log.warn("代码中包含敏感词汇:{}", foundWord.getFoundWord());
//            return null;
//        }


        //实际情况将inputList,code传入代码沙箱,获取memory,time,message和outputList
        log.info("代码沙箱开始执行...");
        //1. 把用户的代码保存为文件
        String userDir = System.getProperty("user.dir");
        String golbalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        if (!FileUtil.exist(golbalCodePathName)) {
            FileUtil.mkdir(golbalCodePathName);
        }
        //将不同用户的提交代码进行隔离
        String userCodeParentPath = golbalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        //2. 编译文件 => .class
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsoluteFile());
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage compileExecuteMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            log.info(compileExecuteMessage.toString());
        } catch (IOException e) {
            e.printStackTrace();
            return getErrorResponse(e);
        }

        //3. 执行.class文件,获取执行结果
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath, inputArgs);
//            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s;%s -Djava.security.manager=%s Main %s", userCodeParentPath, SECURITY_MANAGER_PATH, SECURITY_MANAGER_CLASS_NAME, inputArgs);
            try {
                Process runProcess = Runtime.getRuntime().exec(runCmd);
                ExecuteMessage runExecuteMessage = ProcessUtils.runProcessAndGetMessage(runProcess, "运行");
                log.info(runExecuteMessage.toString());
                executeMessageList.add(runExecuteMessage);
            } catch (IOException e) {
                e.printStackTrace();
                return getErrorResponse(e);
            }
        }
        //4. 封装结果,构造响应对象
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        // 输出用例 , 执行时间(取用时最大值，便于判断是否超时)
        long maxTime = 0;
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                // 用户提交的代码执行中存在错误
                executeCodeResponse.setMessage("3");
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
        }
        // 正常运行完成
        if (outputList.size() == executeMessageList.size()) {
            // 用户提交的代码正常运行完成
            executeCodeResponse.setMessage("1");
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        //执行内存
        // 要借助第三方库来获取内存占用，非常麻烦，此处不做实现

        executeCodeResponse.setJudgeInfo(judgeInfo);


        //5. 文件清理
//        if (userCodeFile.getParent() != null){
//            boolean del = FileUtil.del(userCodeParentPath);
//            System.out.println("删除" + (del ? "成功" : "失败"));
//        }
        //日志记录
        log.info("代码沙箱执行完毕...");


        //返回结果
        return executeCodeResponse;
    }

    /**
     * 获取错误处理
     *
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());

        // 表示代码沙箱错误
        executeCodeResponse.setMessage("2");
        executeCodeResponse.setJudgeInfo(new JudgeInfo());

        return executeCodeResponse;
    }
}
